var express = require('express');
var router = express.Router();
var sql = require('./../tool/sql');

/* GET users listing. */
//查询
router.get('/', function(req, res, next) {
  sql.find('news', {}, {_id: 0}).then(data => {
    console.log(data)
    data.sort((a,b) => {
      return b.tid - a.tid;
    });
    sql.distinct('news', 'type').then(arr => {
      res.render('news', {
        result: data,
        kind: arr
      })
    });
    // res.render('news', {
    //   result: data
    // })
  }).catch(err => console.log(err))
});

//添加
router.get('/add', function(req, res, next) {
  const insertData = req.query;  //路由的名字和个数
  sql.insert('news', insertData).then(() => {
    res.redirect('/news')
  }).catch(err => console.log(err))
})

//删除
router.get('/delete',function(req, res, next) {
  const deleteData = req.query;
  sql.remove('news',deleteData).then(() => {
    res.redirect('/news')
  }).catch(err => console.log(err))
})

// router.get('/detail',function(req, res, next) {
//   const obj = req.query;
//   const tid = { tid: obj.tid };
//   console.log(tid)
//   sql.find('news',tid).then(() => {
//     res.render('newsdetail', {
//       result: data[0]
//     })
//   }).catch(err => console.log(err))
// })
//修改
router.get('/updateOne', function(req, res, next) {
  const obj = req.query; // req.query  --- {username:'', run: 2}
  const whereData = { tid: obj.tid };
  const updateData = {
    $set: obj
  }
  sql.updateOne('news', whereData, updateData).then(() => {
    res.redirect('/news')
  }).catch(err => console.log(err))
});
//类型
router.get('/type', function (req, res, next) {
  let obj = req.query; // {num:''}
  var arr = [];
  arr.push(obj.num)
  sql.find('news', {type: obj.num}, {}).then(data => {
    console.log(data)
    // res.send(data)
    res.render('news', {
      result: data,
      kind: arr
    })
  })
});
//搜索
router.get('/search', function (req, res, next) {
  const obj = req.query; // {username:''}
  sql.find('news', {title: eval('/' + obj.title + '/')}, {}).then(data => {
    console.log(data)
    sql.distinct('news', 'title').then(arr => {
      res.render('news', {
        result: data,
        kind: ""
      })
    });
  })
})
router.get('/kind', function (req, res, next) {
  const obj = req.query;
  sql.distinct('news', 'type').then(data => {
    res.send(data)
  });
});
module.exports = router;